package org.example.service.serviceimpl;

import lombok.extern.slf4j.Slf4j;
import org.example.dto.UserLoginDto;
import org.example.entity.Condition;
import org.example.entity.User;
import org.example.mapper.UserMapper;
import org.example.properties.JwtProperties;
import org.example.service.UserService;
import org.example.utils.JwtUtil;
import org.example.vo.UserVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Service
@Slf4j
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private JwtUtil jwtUtil = new JwtUtil();
    @Autowired
    private JwtProperties jwtProperties;
    /**
     * 登录
     * @param userLoginDto
     * @return
     */
    @Override
    public UserVO login(UserLoginDto userLoginDto) {
        User user = userMapper.login(userLoginDto);
        log.info("user:{}",user);
        UserVO userVO = new UserVO();
        if (user != null) {
            /**
             * 将用户名包装成token，返回给前端
             */
            Map map = new HashMap();
            map.put("username", user.getUsername());
            map.put("userId", user.getUserId());
            map.put("role", user.getRole());
            String token = jwtUtil.createJWT(jwtProperties.getSecretKey(), jwtProperties.getTtl(),map);
            userVO.setToken(token);
            userVO.setUserId(user.getUserId());
            userVO.setEmail(user.getEmail());
            userVO.setPhoneNumber(user.getPhoneNumber());
            userVO.setFullName(user.getFullName());
            return userVO;
        }
        return null;
    }

    /**
     * 用户注册
     * @param userLoginDto
     * @return
     */
    @Override
    public Boolean register(UserLoginDto userLoginDto) {
        log.info("用户注册：{}", userLoginDto);
        if (userMapper.login(userLoginDto) != null) {
            return false;
        }
        User user=new User();
        user.setUsername(userLoginDto.getUsername());
        user.setPasswordHash(userLoginDto.getPasswordHash());
        Boolean result=userMapper.insert(user);
        return result;
    }

    /**
     * 用户信息完善
     * @param userVO
     */
    @Override
    public Boolean perfectInformation(UserVO userVO) {
        log.info("用户信息完善：{}",userVO);
        Boolean result=userMapper.update(userVO);
        return result;
    }

    /**
     * 获取全部老师信息
     * @return
     */
    @Override
    public List<User> getuser() {
        List<User> users = userMapper.getuser();
        return users;
    }

    /**
     * 根据条件查询用户信息
     * @param condition
     * @return
     */
    @Override
    public List<User> getUserInfo(Condition condition) {
        List<User> list=userMapper.getUserInfo(condition);
        return list;
    }
}
